<?php
declare (strict_types = 1);

namespace app\attachment\controller;

class File extends Base
{
    private $allow_extension = ['jpeg', 'jpe', 'jpg', 'gif', 'png', 'webp'];
    private $addition_water = false;
    // protected $file_system;
    protected function initialize()
    {
        parent::initialize();
    }
    public function single(){
        // 获取表单上传文件
        $file = request()->file('file');
        $hash = $file->hash('sha1');
        $attachment = $this->model->where('hash',$hash)->find();
        if($attachment !== null){
            return json($attachment);
        } else {
            $module = request()->param('module', 'common');
            // 验证上传内容
            try {
                // validate(['image'=>'filesize:10240|fileExt:jpg|image:200,200,jpg'])->check([$file]);
                // 上传到本地服务器
                $savename =  \think\facade\Filesystem::putFile($module, $file);
            } catch (think\exception\ValidateException $e) {
                return json($e->getMessage(),500);
            }
            $url =  \think\facade\Filesystem::getConfig('disks.public.url');

            $attachment = [];
            $attachment['filename'] = $file->getOriginalName();
            $attachment['filepath'] = $savename;
            $attachment['filesize'] = $file->getSize();
            $attachment['fileext'] = $file->getOriginalExtension();
            $attachment['uploader_id'] = request()->uid;
            $attachment['is_cover'] = false;
            $attachment['water'] = false;
            $attachment['url'] = $attachment['location'] =$this->get_server_url($url.'/'.$savename);
            $attachment['hash'] = $file->hash('sha1');
            $attachment['module'] = $module;
            if($this->save_log){
                $this->model->save($attachment);
            }
            return json($attachment);
        }
    }
}
